package www.ld.com.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

@Component
@Slf4j
public class JwtAccessTokenConfig {
    @Resource
    private CustomerAccessTokenConverter customerAccessTokenConverter;

    private static final String PUBLIC_KEY_PATH = "public-key.txt";

    private String getPubKey() {
        ClassPathResource resource = new ClassPathResource(PUBLIC_KEY_PATH);
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
            BufferedReader br = new BufferedReader(inputStreamReader);
            return br.lines().collect(Collectors.joining("\n"));
        } catch (IOException ioe) {
            return null;
        }
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwt = new JwtAccessTokenConverter();
        jwt.setVerifierKey(getPubKey());
        jwt.setAccessTokenConverter(customerAccessTokenConverter);
        return jwt;
    }
}
